<?php
namespace app\middleware;

use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;
use Tinywan\Jwt\JwtToken;

class AuthMiddleware implements MiddlewareInterface
{
    public function process(Request $request, callable $handler): Response
    {
        // 以下路由不需要验证token
        $notNeedAuth = [
            '/api/user/login'
        ];
        
        // 如果是不需要验证的路由，直接通过
        if (in_array($request->path(), $notNeedAuth)) {
            return $handler($request);
        }

        // 验证token
        try {
            // 获取当前用户id
            $uid = JwtToken::getCurrentId();
            // 验证通过，将用户ID添加到request中
            $request->uid = $uid;
            // 继续执行
            return $handler($request);
        } catch (\Exception $e) {
            // token验证失败
            return json([
                'code' => 401,
                'msg' => $e->getMessage()
            ]);
        }
    }
} 